﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.Auth.Service.OAuth
{
    public class RefreshTokenRepository
    {
        private readonly IMongoCollection<RefreshToken> _refreshTokenCollection;

        public RefreshTokenRepository(IMongoCollection<RefreshToken> refreshTokenCollection)
        {
            _refreshTokenCollection = refreshTokenCollection;
        }

        public virtual async Task<RefreshToken> GetByIdAsync(string tokenId)
        {
            Guid id;
            if (!Guid.TryParse(tokenId, out id))
                return null;

            return await _refreshTokenCollection.AsQueryable().FirstOrDefaultAsync(x => x.Id == id);
        }

        public virtual async Task AddAsync(RefreshToken refreshToken)
        {
            await _refreshTokenCollection.InsertOneAsync(refreshToken);
        }

        public virtual async Task RemoveAsync(string tokenId)
        {
            Guid id;
            if (!Guid.TryParse(tokenId, out id))
                return;

            await _refreshTokenCollection.DeleteOneAsync(x => x.Id == id);
        }
    }
}
